package com.firmiana.jt809.netty.sub;

import com.firmiana.jt809.config.GlobalConfig;
import com.firmiana.jt809.entity.JT809Message;
import com.firmiana.jt809.protocol.IReceiveProtocol;
import com.firmiana.jt809.util.SpringUtils;
import com.firmiana.jt809.util.Tools;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * 从链路处理器
 * @author hucl
 * @date 2020/8/26 10:12
 */
@Slf4j
public class SubLinkHandler extends SimpleChannelInboundHandler<JT809Message> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JT809Message msg) throws Exception {
        String data = "";
        int protocolId = msg.getMsgType();
        log.info("上级平台【从链路】收到下级平台发送的报文指令：0x" + Integer.toHexString(protocolId));
        if (GlobalConfig.getReceiveProtocolByProtocolId(protocolId) != null) {
            try {
                IReceiveProtocol protocolClass = SpringUtils.getBean(GlobalConfig.getReceiveProtocolByProtocolId(protocolId));
                data = protocolClass.handle(msg);
            } catch (Exception e) {
                log.error("【从链路】解析协议出错:" + msg.toHexString() , e);
            }
            msg.setRemark("主下行 MSG!");
            // 接收到命令，如果需要应答，就返回应答数据，由socket连接发送应答
            if ((data != null) && (data.length() > 0)) {
                ctx.channel().writeAndFlush(data);
            }
        } else {
            log.error("上级平台【从链路】没有找到处理协议类型的类：" + Tools.toHexString(protocolId, 2));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("【从链路链路】channel读取异常:" + cause.getMessage(), cause);
        cause.printStackTrace();
        ctx.close();
    }
}
